﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
using SQLTool;
using SshNet;
using BLL;
using SSHTool;
using System.Text.RegularExpressions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Model;
using System.Net.NetworkInformation;
using Emgu.CV.Ocl;
using Renci.SshNet.Messages;
using System.Net;
using Microsoft.Data.SqlClient;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace NetworkOPSUI
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();

        }
        #region 基础操作 页面部分
        bool connectionState = false;
        public string OPip = "";
        public SSHTool sshTool;
        DataTable CommandTable = new DataTable();
        public SSHTooltest ssh;
        public List<IPCdevice> CheckedIPCDevicesList = new List<IPCdevice>();
        int checkedNodeCount;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            DeviceManageInit();  //设备管理 模块初始化
            comboBox_command.Text = "选择快捷操作指令";
            comboBox_TASK_Comm.Text = "选择快捷操作指令";
            //LoadComoBoxCommand(comboBox_command);
            //LoadComoBoxCommand(comboBox_TASK_Comm);
            LoadDevicesToTreeView();  //加载设备分组
            CommandTable = BLL.Preload.PreLoadCommandTable(); //预加载 快捷命令表
        }
        private void button_Conn_Click(object sender, EventArgs e) //设备连接
        {
            if (OPip == null)
            { MessageBox.Show("请先选中左侧设备", "操作提示"); }
            else
            {
                try
                {
                    sshTool = new SSHTool(OPip, "ycjc", "Wdxs#7799", richTextBox_output);
                    if (sshTool.Connect())
                    {
                        connectionState = true;
                        richTextBox_output.Clear();
                        AddRichTextBox(richTextBox_output, "设备连接成功" + "\n");
                    }
                    else
                    {
                        MessageBox.Show("设备连接失败", "操作提示");
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        private void button_Disconn_Click(object sender, EventArgs e)
        {

            if (connectionState == true)
            {
                if (sshTool.Disconnect())
                {
                    connectionState = false;
                    AddRichTextBox(richTextBox_output, "已经断开连接");
                }
                else MessageBox.Show("断开连接失败！", "操作提示");
            }
            else
            {
                MessageBox.Show("当前未连接设备", "操作提示");
            }
        }

        //执行单一操作指令
        private void runSingleCommand(string comm)
        {
            string recult = Convert.ToString(ssh.SendCommand(comm));
            AddRichTextBox(richTextBox_output, recult);
        }

        //异步 流式执行执行指令
        private async void runStreamCommand(string command)
        {
            if (ssh.Connect())
            {
                await Task.Run(() => ssh.SendCommandByStream(command)); // 用你需要的命令替换
                // 这会开始一个无限循环，持续读取数据
                int i = 5;
                AddRichTextBox(richTextBox_output, ssh.ContinuousRead());
            }
            else
            {
                AddRichTextBox(richTextBox_output, "Failed to connect.");
            }
        }
        private void button_execute_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox_command.SelectedIndex == 8)
                {
                    FrmSafety frmSafety = new FrmSafety();
                    frmSafety.ShowDialog();
                    MessageBox.Show("验证通过");
                }
                else
                {
                    if (!connectionState) { MessageBox.Show("请先连接设备", "操作提示"); }
                    else
                    {
                        string comm = textBox_commContent.Text;
                        //runSingleCommand(comm);
                        // runStreamCommand(comm);
                        sshTool.SendCommandWithShellStream(comm);
                        //sshTool.SendCommand(comm);
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString(), "错误提示");
            }
        }


        public void AddRichTextBox(RichTextBox richTextBox, string text)
        {
            richTextBox.AppendText(text);
            // 将光标设置到文本的末尾
            richTextBox.SelectionStart = richTextBox.Text.Length;
            // 滚动到光标位置
            richTextBox.ScrollToCaret();
        }

        private void LoadDevicesToTreeView()
        {
            treeView_Devices.Nodes.Clear(); // 清空原有节点
            DataTable dataTable = SQLOPT.ExecuteQuery("SELECT * FROM DevicesGroup");
            treeView_Devices.BeginUpdate();
            // 加载根节点
            foreach (DataRow row in dataTable.Select("ParentID IS NULL"))
            {
                TreeNode newNode = CreateNodeFromRow(row);
                treeView_Devices.Nodes.Add(newNode);
                LoadChildNodes(newNode, dataTable);
            }
            treeView_Devices.EndUpdate();
        }

        private TreeNode CreateNodeFromRow(DataRow row)
        {
            TreeNode node = new TreeNode(row["DeviceName"].ToString())
            {
                Tag = row["DeviceID"],
                Name = row["DeviceIP"].ToString(),
            };
            return node;
        }

        private void LoadChildNodes(TreeNode parentNode, DataTable dataTable)
        {
            int parentId = (int)parentNode.Tag;

            foreach (DataRow row in dataTable.Select($"ParentID = {parentId}"))
            {
                TreeNode childNode = CreateNodeFromRow(row);
                parentNode.Nodes.Add(childNode);

                // 递归调用添加此节点的子节点
                LoadChildNodes(childNode, dataTable);
            }
        }

        private void comboBox_command_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_command.SelectedIndex != 0)
            {
                var command = (Command)comboBox_command.SelectedItem;
                textBox_commContent.Text = command.CommandContent;
            }

        }
        /// <summary>
        /// Treeview_Devices 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView_Devices_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            richTextBox_Detail.Clear();
            string DeviceIp = e.Node.Name;
            try
            {
                if (DeviceIp.Length > 1)  //判断选中的节点是否为 设备节点
                {
                    if (tabControl1.SelectedIndex == 0)  //当处于快捷操作 页面时
                    {
                        string query = "SELECT * FROM NetworkDevice WHERE NetDeviceIp LIKE " + "'" + DeviceIp + "'";
                        DataTable dt = SQLOPT.ExecuteQuery(query);
                        if (dt != null)
                        {
                            string tt = dt.Rows[0][1].ToString();
                            OPip = dt.Rows[0][2].ToString();
                            richTextBox_Detail.AppendText(tt + "\n" + "IP地址：" + dt.Rows[0][2]);
                            richTextBox_Detail.AppendText("\n" + "备注：" + dt.Rows[0][5]);
                        }
                        LoadCommandByDeviceIp(DeviceIp);
                    }

                    if (tabControl1.SelectedIndex == 2)  //当处于监控自动巡查 页面时
                    {
                        CheckedIPCDevicesList.Clear();
                    }

                    if (tabControl1.SelectedIndex == 3)  //当处于设备管理 页面时
                    {
                        MessageBox.Show("请选中设备分组", "操作提示");
                    }
                }
                else     //否则为 组节点
                {
                    if (tabControl1.SelectedIndex == 3)  //当处于设备管理 页面时
                    {
                        label_GroupTip.Text = "向【" + e.Node.Text + "】分组内添加设备";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "设备选择中发生错误");
            }
        }
        /// <summary>
        /// 根据IP地址，加载comboBox中的内容
        /// </summary>
        /// <param name="ip"></param>
        private void LoadCommandByDeviceIp(string ip)
        {
            try
            {
                string SQLquery = "SELECT NetDeviceType FROM NetworkDevice WHERE NetDeviceIp = '" + ip + "'";
                var commandType = SQLOPT.ExecuteScalar(SQLquery);
                List<Command> commandList = new List<Command>();
                foreach (DataRow dr in CommandTable.Rows)
                {

                    if (dr["CommandMatchType"].ToString() == commandType.ToString())
                    {
                        Command cmd = new Command
                        {
                            CommandName = dr["CommandName"].ToString(),
                            CommandContent = dr["CommandContent"].ToString()
                        };
                        comboBox_command.Items.Add(cmd);
                        comboBox_TASK_Comm.Items.Add(cmd);
                    }
                }
                comboBox_command.DisplayMember = "CommandName";
                comboBox_TASK_Comm.DisplayMember = "CommandName";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "LoadCommand() 错误提示");
            }
        }


        #endregion

        #region 智能运维管理 页面
        private void button_Add_Dev_Task_Click(object sender, EventArgs e)
        {

            CopyCheckedNodesToTask();

        }



        private void CopyCheckedNodesToTask()
        {
            //treeView_Dev_Task.Nodes.Clear();  // 清除treeView_Dev_Task中的所有节点

            foreach (TreeNode node in treeView_Devices.Nodes)
            {
                if (node.Checked)
                {
                    TreeNode newNode = (TreeNode)node.Clone();  // 克隆选中的节点
                    newNode.Text = newNode.Text + newNode.Name;
                    treeView_Dev_Task.Nodes.Add(newNode);
                }
                // TreeView有子节点，需要递归地检查子节点
                CheckAndCopyChildNodes(node, treeView_Dev_Task);
            }
        }
        private void CheckAndCopyChildNodes(TreeNode parentNode, System.Windows.Forms.TreeView targetTreeView)
        {
            foreach (TreeNode childNode in parentNode.Nodes)
            {
                if (childNode.Checked)
                {
                    TreeNode newNode = (TreeNode)childNode.Clone();  // 克隆选中的子节点
                    newNode.Text = newNode.Text + newNode.Name;
                    targetTreeView.Nodes.Add(newNode);
                }
                // 递归地检查子节点的子节点
                CheckAndCopyChildNodes(childNode, targetTreeView);
            }
        }
        private void button_ClearTASK_Click(object sender, EventArgs e)
        {
            treeView_Dev_Task.Nodes.Clear();
        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                LoadDevicesToTreeView();
                treeView_Devices.CheckBoxes = true;
                checkedNodeCount = 0;
            }
            if (tabControl1.SelectedIndex == 0)
            {
                LoadDevicesToTreeView();
                treeView_Devices.CheckBoxes = false;
            }
            if (tabControl1.SelectedIndex == 2)
            {
                treeView_Devices.CheckBoxes = true;
                LoadIPCtoTreeView();
                checkedNodeCount = 0;
            }
            if (tabControl1.SelectedIndex == 3)
            {
                LoadDevicesToTreeView();
                treeView_Devices.CheckBoxes = false;
                richTextBox_DeviceDetail.Focus();
                tabControl1.Focus();
                treeView_Devices.SelectedNode = null;
            }

        }

        private void progressBar_OPS_Click(object sender, EventArgs e)
        {
            progressBar_OPS.Value = progressBar_OPS.Value + progressBar_OPS.Step;
        }

        private void comboBox_TASK_Comm_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_TASK_Comm.SelectedIndex != 0)
            {
                var command = (Command)comboBox_TASK_Comm.SelectedItem;
                richTextBox_Task_comm.Text = command.CommandContent;
            }
        }



        #endregion


        #region 监控自动巡查

        public void LoadIPCtoTreeView()
        {

            //DataTable IPCGroupMap = SQLOPT.ExecuteQuery("SELECT * FROM IPCGroupMapping");

            DataTable resultTable = SQLOPT.ExecuteQuery("SELECT \r\n  g.GroupName, d.CameraName, d.CameraIp  -- 更多设备信息字段...\r\nFROM \r\n  IPCGroup g\r\nINNER JOIN \r\n  IPCGroupMapping gm ON g.GroupId = gm.GroupId\r\nINNER JOIN \r\n  IPCDevice d ON gm.CameraId = d.CameraId\r\nORDER BY \r\n  g.GroupName, d.CameraName; -- 按照组名和IPC名称排序");
            //treeView_Devices.BeginUpdate();


            // 假设已执行查询并得到数据 DataTable resultTable
            treeView_Devices.Nodes.Clear(); // 清空原有节点

            // 遍历查询结果，按组名分组
            var groups = resultTable.AsEnumerable()
                .GroupBy(row => row.Field<string>("GroupName"));

            foreach (var group in groups)
            {
                var groupName = group.Key;
                var parentNode = new TreeNode(groupName);

                foreach (var deviceRow in group)
                {
                    var ipcName = deviceRow.Field<string>("CameraName");
                    var ipAddress = deviceRow.Field<string>("CameraIp");

                    var deviceNode = new TreeNode($"{ipcName} ({ipAddress})");
                    deviceNode.Tag = ipAddress; // 将IP地址保存到节点的Tag属性中

                    parentNode.Nodes.Add(deviceNode);
                }

                treeView_Devices.Nodes.Add(parentNode);
            }

            // 如果需要，还可以进一步对节点进行排序或其他自定义操作
            treeView_Devices.ExpandAll(); // 展开所有节点以便查看
        }
        /// <summary>
        /// 检查区间内设备是否在线，结果输出到richtextbox
        /// </summary>
        /// <param name="listIP"></param>
        /// <param name="richtextbox_out"></param>
        private async Task CheckDevicesAndOutput(List<string> listIP, RichTextBox richtextbox_out)
        {
            progressBar_Inspect.Minimum = 0;
            progressBar_Inspect.Maximum = listIP.Count;
            progressBar_Inspect.Value = 0;
            string woring = "";
            foreach (var ip in listIP)
            {
                var result = await PingAsync(ip);
                if (result.Status == IPStatus.Success)
                    AddRichTextBox(richtextbox_out, $"{ip} 设备检测正常—在线\n");
                else
                {
                    woring = woring + "【" + ip.ToString() + "】";
                    AddRichTextBox(richtextbox_out, $"{ip} 设备异常！掉线\n");
                }
                progressBar_Inspect.Value++;  // 更新进度条
            }
            if (woring != "")
            {
                AddRichTextBox(richtextbox_out, "发现掉线设备:" + woring + "\n");
            }
        }
        /// <summary>
        /// 检查 List<IPCdevice> 中设备是否在线 并输出结果到richtextbox
        /// </summary>
        /// <param name="listIPC"></param>
        /// <param name="richtextbox_out"></param>
        private async Task CheckByIPCDeviceAndOutput(List<IPCdevice> listIPC, RichTextBox richtextbox_out)
        {
            progressBar_Inspect.Minimum = 0;
            progressBar_Inspect.Maximum = listIPC.Count;
            progressBar_Inspect.Value = 0;
            string woring = "";
            foreach (var iPCdevice in listIPC)
            {
                var result = await PingAsync(iPCdevice.CameraIP);
                if (result.Status == IPStatus.Success)
                    AddRichTextBox(richtextbox_out, $"\n{iPCdevice.CameraName}[{iPCdevice.CameraIP}] 设备检测正常—在线");
                else
                {
                    woring = woring + "【" + iPCdevice.CameraIP + "】";
                    AddRichTextBox(richtextbox_out, $"\n{iPCdevice.CameraName}[{iPCdevice.CameraIP}] 设备异常！已离线");
                }
                progressBar_Inspect.Value++;  // 更新进度条
            }
            if (woring != "")
            {
                AddRichTextBox(richtextbox_out, "\n" + "发现离线设备:" + woring);
            }

        }
        private Task<PingReply> PingAsync(string ipAddress)
        {
            var ping = new Ping();
            return ping.SendPingAsync(ipAddress);
        }



        private async void button_IPCinspect_Click(object sender, EventArgs e)
        {
            string starIp = textBox_statIP.Text;
            string endIp = textBox_endIP.Text;
            DisableButtonsInPanel(panel_IPC); // 禁用panel_IPC内所有Button控件
            try
            {
                // 验证开始地址和结束地址的有效性
                if (string.IsNullOrEmpty(starIp) || string.IsNullOrEmpty(endIp))
                {
                    MessageBox.Show("开始地址和结束地址不能为空", "操作提示");
                }
                else
                {
                    // 检查开始地址不小于结束地址
                    if (starIp[0] > endIp[0] || (starIp[0] == endIp[0] && starIp[1] > endIp[1]))
                    {
                        MessageBox.Show("开始地址必须在结束地址之前", "操作提示");
                    }
                    else
                    {
                        IPaddressConvert converter = new IPaddressConvert();
                        List<string> ipList = converter.GenerateIPRange(starIp, endIp);
                        await CheckDevicesAndOutput(ipList, richTextBox_InspectOut);
                        EnableButtonsInPanel(panel_IPC);  //启用Button控件
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "系统出错");
            }
            finally
            {
                textBox_statIP.Focus();
               
            }
            EnableButtonsInPanel(panel_IPC);  //启用Button控件
        }

        //编写一个异步方法，对范围内IP进行检查，将网络可达的IP写入List<string>
        private async Task<List<string>> CheckDevicesAsync(List<string> listIP)
        {
            List<string> list = new List<string>();
            foreach (var ip in listIP)
            {
                var result = await PingAsync(ip);
                if (result.Status == IPStatus.Success)
                    list.Add(ip);
            }
            return list;
        }


        private void button_PICipInspect_Click(object sender, EventArgs e)  //IP地址监控巡查
        {

            string starIp = textBox_statIP.Text;
            string endIp = textBox_endIP.Text;
            List<string> Iplist = new List<string>();
            try
            {
                // 验证开始地址和结束地址的有效性
                if (string.IsNullOrEmpty(starIp) || string.IsNullOrEmpty(endIp))
                {
                    MessageBox.Show("开始地址和结束地址不能为空", "操作提示");
                }
                else
                {
                    // 检查开始地址不小于结束地址
                    if (starIp[0] > endIp[0] || (starIp[0] == endIp[0] && starIp[1] > endIp[1]))
                    {
                        MessageBox.Show("开始地址必须在结束地址之前", "操作提示");
                    }
                    else
                    {
                        IPaddressConvert converter = new IPaddressConvert();
                        Iplist = converter.GenerateIPRange(starIp, endIp);
                        //CheckDevicesAndOutput(ipList, richTextBox_InspectOut);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "系统出错");
            }
            finally
            {
                textBox_statIP.Focus();
            }
            FrmOperatte frmOperatte = new FrmOperatte();
            frmOperatte.ShowDialog();
        }





        // 递归方法，遍历所有子节点 获取选中的结点
        private void GetCheckedNodes(TreeNode parentNode, List<string> checkedIPList)
        {
            foreach (TreeNode childNode in parentNode.Nodes)
            {
                if (childNode.Checked)
                {
                    if (childNode.Tag != null)
                    {
                        checkedIPList.Add(childNode.Tag.ToString());
                    }

                    // 递归检查孙子节点等后代节点
                    GetCheckedNodes(childNode, checkedIPList);
                }
            }
        }


        //Button 按分组巡查响应事件
        private async void button_GroupInspect_Click(object sender, EventArgs e)
        {
            DisableButtonsInPanel(panel_IPC); // 禁用panel_IPC内所有Button控件
            //获取 treeView_Devices 选中的所有结点的Node.Tag, 写入 List<string> checkedIP
            List<string> checkedIP = new List<string>();

            CheckedIPCDevicesList.Clear();

            // 获取treeview当前选中的所有节点
            foreach (TreeNode node in treeView_Devices.Nodes)
            {
                if (node.Checked)
                {

                    // 检查当前节点是否选中
                    if (node.Tag != null)
                    {
                        // 如果Tag属性不为空，则将其转换为字符串并添加到列表中
                        checkedIP.Add(node.Tag.ToString());
                    }
                }
                // 遍历子节点
                GetCheckedNodes(node, checkedIP);

            }
            DataTable IPCdevices = SQLOPT.ExecuteQuery("SELECT * FROM IPCDevice");
            List<IPCdevice> iPCdevices = await GetDevicesByIPAsync(checkedIP, IPCdevices);

            await CheckByIPCDeviceAndOutput(iPCdevices, richTextBox_InspectOut);

            EnableButtonsInPanel(panel_IPC);  //启用Button控件
        }

        //禁用Panel内所有Button控件的方法
        private void DisableButtonsInPanel(Control parentControl)
        {
            foreach (Control control in parentControl.Controls)
            {
                if (control is System.Windows.Forms.Button)
                {
                    control.Enabled = false;
                }
                else if (control is GroupBox || control is Panel) // 处理GroupBox和可能存在的其他Panel
                {
                    DisableButtonsInPanel(control); // 递归处理GroupBox或Panel内的控件
                }
            }
        }

        // 恢复指定Panel内所有Button控件的方法
        private void EnableButtonsInPanel(Control parentControl)
        {
            foreach (Control control in parentControl.Controls)
            {
                if (control is System.Windows.Forms.Button)
                {
                    control.Enabled = true;
                }
                else if (control is GroupBox || control is Panel) // 处理GroupBox和可能存在的其他Panel
                {
                    EnableButtonsInPanel(control); // 递归处理GroupBox或Panel内的控件
                }
            }
        }

        // 递归方法，用于设置所有子节点的选中状态
        private void CheckAllChildren(TreeNode parentNode, bool checkState)
        {
            foreach (TreeNode childNode in parentNode.Nodes)
            {
                childNode.Checked = checkState;

                // 如果子节点还有孙子节点，则继续递归
                if (childNode.Nodes.Count > 0)
                {
                    CheckAllChildren(childNode, checkState);
                }
            }
        }

        //设置treeView中结点，选中/取消选中时，同步子节点选中状态
        private void treeView_Devices_AfterCheck(object sender, TreeViewEventArgs e)
        {
            // 当父节点被检查时
            if (e.Node.Nodes.Count > 0)
            {
                // 自动勾选或取消勾选所有子节点
                CheckAllChildren(e.Node, e.Node.Checked);
            }


            // 清零计数器，重新开始计数（防止累加）
            checkedNodeCount = 0;
            // 遍历整个TreeView的所有根节点以获取最新选中的节点数量
            foreach (TreeNode rootNode in treeView_Devices.Nodes)
            {
                UpdateAndGetCheckedNodesCount(rootNode.Nodes);
            }
            // 更新文本框显示
            textBox_CheckedNum.Text = checkedNodeCount.ToString();
        }


        // 更新并获取已选中节点数量的方法（处理多根节点）
        private void UpdateAndGetCheckedNodesCount(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Checked)
                {
                    checkedNodeCount++;
                }
                // 递归检查子节点
                UpdateAndGetCheckedNodesCount(node.Nodes);
            }
        }


        public async Task<List<IPCdevice>> GetDevicesByIPAsync(List<string> checkedIP, DataTable IPdeviceTable)
        {
            List<IPCdevice> IPClist = new List<IPCdevice>();

            foreach (string ip in checkedIP)
            {
                DataRow[] matchedRows = IPdeviceTable.Select($"CameraIp = '{ip}'");

                foreach (DataRow row in matchedRows)
                {
                    IPCdevice device = new IPCdevice
                    {
                        CameraIP = row.Field<string>("CameraIp"),
                        CameraName = row.Field<string>("CameraName"),
                        RtspUrl = row.Field<string>("RtspURL"),
                        UserName = row.Field<string>("UserName"),
                        Password = row.Field<string>("PassWord"),
                        // 更多字段...
                    };
                    IPClist.Add(device);
                }
            }
            return IPClist;
        }
        private void button_PICGroupInspect_Click(object sender, EventArgs e)
        {


            //MessageBox.Show(groupBox2.Parent.Name.ToString());
        }











        #endregion


        #region 设备管理
        public void DeviceManageInit()
        {

            comboBox_DeviceType.Items.Add("交换机");
            comboBox_DeviceType.Items.Add("服务器");
            comboBox_DeviceType.SelectedIndex = 0;
            richTextBox_DeviceDetail.Focus();
            comboBox_Auth.SelectedIndex = 0;
        }
        /// <summary>
        /// 检查 IP地址是否有效
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsValidIP(string ip)
        {
            // 有效的IPv4地址格式为 "xxx.xxx.xxx.xxx"，其中每个 "xxx" 是一位0-255的数字
            string pattern = @"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$";

            // 检查输入的IP地址是否符合我们定义的正则表达式
            return System.Text.RegularExpressions.Regex.IsMatch(ip, pattern);
        }
        private void richTextBox_DeviceDetail_LostFocus(object sender, EventArgs e)
        {
            if (richTextBox_DeviceDetail.Text == "")
            {
                richTextBox_DeviceDetail.Text = "输入设备详情信息:";
            }
            //显示的字体颜色，灰色
            richTextBox_DeviceDetail.ForeColor = Color.Gray;
        }
        private void richTextBox_DeviceDetail_GotFocus(object sender, EventArgs e)
        {
            if (richTextBox_DeviceDetail.Text == "输入设备详情信息:")
            {
                richTextBox_DeviceDetail.Text = "";
            }
            //输入的字体颜色，黑色
            richTextBox_DeviceDetail.ForeColor = Color.Black;
        }


        private void button_AddDevice_Click(object sender, EventArgs e)
        {
            bool LoadGroupInfo = false;
            bool LoadDeviceInfo = false;

            int GroupID = 0;
            //判断要写入的Group信息是否有效
            if (treeView_Devices.SelectedNode != null)
            {
                if (treeView_Devices.SelectedNode.Tag != "")
                {
                    GroupID = (int)treeView_Devices.SelectedNode.Tag;
                    LoadGroupInfo = true;
                }
                else
                {
                    MessageBox.Show("请选择正确分组", "错误提示");
                }
            }
            else
            {
                MessageBox.Show("请先选中左侧设备分组", "错误提示");
            }

            string deveiceIP = textBox_DeviceIp.Text;
            string deviceName = textBox_DeviceName.Text;
            int deviceType = 1;
            string deviceDetail = richTextBox_Detail.Text;
            int deviceAuth = 1;
            //判断要写入的Device信息是否有效
            if (textBox_DeviceName.Text.Length > 2 && textBox_DeviceIp.Text.Length > 4)
            {

                if (comboBox_Auth.Text == " 二 级") deviceAuth = 2;
                if (comboBox_Auth.Text == " 三 级") deviceAuth = 3;
                if (comboBox_Auth.Text == " 四 级") deviceAuth = 4;
                if (comboBox_Auth.Text == " 五 级") deviceAuth = 5;
                if (comboBox_DeviceType.Text == "服务器") deviceType = 2;

                if (IsValidIP(deveiceIP))
                {
                    LoadDeviceInfo = true;
                }
                else
                {
                    MessageBox.Show("填入的IP地址格式有误！", "错误提示");
                }
            }
            else
            {
                MessageBox.Show("请检查填入的信息，是否正确", "错误提示");
            }
            if (LoadGroupInfo && LoadDeviceInfo)
            {
                string QuerySQL = "SELECT * FROM NetworkDevice WHERE NetDeviceIP = '" + deveiceIP + "'";
                if (SQLOPT.ExecuteQuery(QuerySQL).Rows.Count > 0)
                {
                    MessageBox.Show("设备已存在，请勿重复添加", "操作提示");
                }
                else
                {
                    string sqlGroup = "INSERT DevicesGroup (DeviceName,DeviceIP,ParentID) VALUES (" + "'" + deviceName + "'," + "'" + deveiceIP + "'," + GroupID + ")";
                    string sqlDevices = "INSERT INTO NetworkDevice (NetDeviceName,NetDeviceIP,NetDeviceType,NetDeviceAUTH,NetDeviceRemark) VALUES (" + "'" + deviceName + "'," + "'" + deveiceIP + "'," + deviceType + "," + deviceAuth + ",'" + deviceDetail + "')";

                    if (SQLOPT.ExecuteNonQuery(sqlDevices) == 1 && SQLOPT.ExecuteNonQuery(sqlGroup) == 1)
                    {
                        MessageBox.Show("设备添加成功", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        textBox_DeviceIp.Text = null;
                        textBox_DeviceName.Text = null;
                    }
                    else MessageBox.Show("设备添加失败", "操作提示");
                }
            }
        }

        #endregion


      
    }
}





